<template>
  <a-modal
    v-model:open="visible"
    :title="null"
    :footer="null"
    :width="480"
    :centered="true"
    :closable="false"
    :maskClosable="false"
    class="auth-modal"
  >
    <div class="auth-container">
      <!-- 关闭按钮 -->
      <div class="close-btn" @click="handleClose">
        <CloseOutlined />
      </div>
      
      <!-- Logo和标题 -->
      <div class="auth-header">
        <img src="@/assets/ai/modern-logo.svg" alt="logo" class="auth-logo" />
        <h2 class="auth-title">{{ isLogin ? '欢迎回来' : '加入我们' }}</h2>
        <p class="auth-subtitle">{{ isLogin ? '登录您的账户继续使用' : '创建账户开始您的AI之旅' }}</p>
      </div>

      <!-- 模式切换 -->
      <div class="mode-switch">
        <div class="switch-container">
          <div 
            class="switch-item" 
            :class="{ active: isLogin }"
            @click="switchMode(true)"
          >
            登录
          </div>
          <div 
            class="switch-item" 
            :class="{ active: !isLogin }"
            @click="switchMode(false)"
          >
            注册
          </div>
          <div class="switch-indicator" :class="{ 'move-right': !isLogin }"></div>
        </div>
      </div>

      <!-- 登录表单 -->
      <div v-if="isLogin" class="form-container">
        <a-form
          :model="loginForm"
          name="login"
          @finish="handleLogin"
          :rules="loginRules"
          layout="vertical"
        >
          <a-form-item label="账号" name="userAccount">
            <a-input
              v-model:value="loginForm.userAccount"
              placeholder="请输入用户名"
              size="large"
              class="auth-input"
            >
              <template #prefix>
                <UserOutlined class="input-icon" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="密码" name="userPassword">
            <a-input-password
              v-model:value="loginForm.userPassword"
              placeholder="请输入密码"
              size="large"
              class="auth-input"
            >
              <template #prefix>
                <LockOutlined class="input-icon" />
              </template>
            </a-input-password>
          </a-form-item>

          <div class="form-options">
            <a-checkbox v-model:checked="remember">记住我</a-checkbox>
            <a class="forgot-link" href="#">忘记密码？</a>
          </div>

          <a-form-item>
            <a-button 
              type="primary" 
              html-type="submit" 
              size="large"
              class="auth-button"
              :loading="loading"
            >
              登录
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 注册表单 -->
      <div v-else class="form-container">
        <a-form
          :model="registerForm"
          name="register"
          @finish="handleRegister"
          :rules="registerRules"
          layout="vertical"
        >
          <a-form-item label="账号" name="userAccount">
            <a-input
              v-model:value="registerForm.userAccount"
              placeholder="请输入用户名"
              size="large"
              class="auth-input"
            >
              <template #prefix>
                <UserOutlined class="input-icon" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="密码" name="userPassword">
            <a-input-password
              v-model:value="registerForm.userPassword"
              placeholder="请输入密码"
              size="large"
              class="auth-input"
            >
              <template #prefix>
                <LockOutlined class="input-icon" />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item label="确认密码" name="checkPassword">
            <a-input-password
              v-model:value="registerForm.checkPassword"
              placeholder="请再次输入密码"
              size="large"
              class="auth-input"
            >
              <template #prefix>
                <LockOutlined class="input-icon" />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item>
            <a-button 
              type="primary" 
              html-type="submit" 
              size="large"
              class="auth-button"
              :loading="loading"
            >
              注册
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { CloseOutlined, UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { userLogin, userRegister } from '@/api/userController'
import { useLoginUserStore } from '@/stores/loginUser'
import { useRouter } from 'vue-router'

const props = defineProps<{
  open: boolean
  defaultMode?: 'login' | 'register'
}>()

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'success'): void
}>()

const loginUserStore = useLoginUserStore()
const router = useRouter()

const visible = computed({
  get: () => props.open,
  set: (value) => emit('update:open', value)
})

const isLogin = ref(props.defaultMode === 'login' || props.defaultMode === undefined)
const loading = ref(false)
const remember = ref(true)

// 监听弹窗打开和默认模式变化
watch([() => props.open, () => props.defaultMode], ([newOpen, newMode]) => {
  if (newOpen) {
    isLogin.value = newMode === 'login' || newMode === undefined
  }
})

// 登录表单
const loginForm = reactive({
  userAccount: '',
  userPassword: ''
})

// 注册表单
const registerForm = reactive({
  userAccount: '',
  userPassword: '',
  checkPassword: ''
})

// 表单验证规则
const loginRules = {
  userAccount: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, message: '用户名至少4个字符', trigger: 'blur' },
    { max: 20, message: '用户名最多20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' },
    { max: 20, message: '密码最多20个字符', trigger: 'blur' }
  ]
}

const registerRules = {
  ...loginRules,
  checkPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string) => {
        if (!value) {
          return Promise.reject('请再次输入密码')
        } else if (value !== registerForm.userPassword) {
          return Promise.reject('两次输入的密码不一致')
        } else {
          return Promise.resolve()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 切换模式
const switchMode = (login: boolean) => {
  isLogin.value = login
  // 清空表单
  Object.assign(loginForm, { userAccount: '', userPassword: '' })
  Object.assign(registerForm, { userAccount: '', userPassword: '', checkPassword: '' })
}

// 处理登录
const handleLogin = async (values: typeof loginForm) => {
  loading.value = true
  try {
    const res = await userLogin(values)
    if (res.data.code === 0) {
      await loginUserStore.fetchLoginUser()
      message.success('登录成功')
      handleClose()
      emit('success')
    } else {
      message.error('登录失败: ' + res.data.message)
    }
  } catch {
    message.error('登录失败')
  } finally {
    loading.value = false
  }
}

// 处理注册
const handleRegister = async (values: typeof registerForm) => {
  loading.value = true
  try {
    const res = await userRegister(values)
    if (res.data.code === 0) {
      message.success('注册成功')
      // 注册成功后切换到登录模式
      switchMode(true)
      loginForm.userAccount = values.userAccount
    } else {
      message.error('注册失败: ' + res.data.message)
    }
  } catch {
    message.error('注册失败')
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  // 重置表单
  switchMode(true)
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

.auth-modal :deep(.ant-modal-content) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.auth-container {
  position: relative;
  padding: 40px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: #64748b;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.08);
  transform: scale(1.1);
}

.auth-header {
  text-align: center;
  margin-bottom: 32px;
}

.auth-logo {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
  filter: drop-shadow(0 4px 12px rgba(102, 126, 234, 0.3));
}

.auth-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  letter-spacing: -0.02em;
}

.auth-subtitle {
  font-size: 16px;
  color: #64748b;
  margin: 0;
  font-weight: 400;
}

.mode-switch {
  margin-bottom: 32px;
}

.switch-container {
  position: relative;
  display: flex;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  padding: 4px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.switch-item {
  flex: 1;
  text-align: center;
  padding: 12px 24px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 8px;
  position: relative;
  z-index: 2;
}

.switch-item.active {
  color: #667eea;
  font-weight: 600;
}

.switch-indicator {
  position: absolute;
  top: 4px;
  left: 4px;
  width: calc(50% - 4px);
  height: calc(100% - 8px);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.switch-indicator.move-right {
  transform: translateX(100%);
}

.form-container {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  padding: 24px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.auth-input {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.auth-input:hover {
  border-color: #667eea;
}

.auth-input:focus-within {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.input-icon {
  color: #94a3b8;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.forgot-link {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.forgot-link:hover {
  color: #5a6fd8;
  text-decoration: underline;
}

.auth-button {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-weight: 600;
  font-size: 16px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.auth-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.auth-button:active {
  transform: translateY(0);
}

/* 表单标签样式 */
.form-container :deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #374151;
}

/* 复选框样式 */
.form-container :deep(.ant-checkbox-wrapper) {
  font-weight: 400;
  color: #64748b;
}

.form-container :deep(.ant-checkbox-checked .ant-checkbox-inner) {
  background-color: #667eea;
  border-color: #667eea;
}
</style>